#pragma once


//#include <adojet.h>
#include "base/StructType.hpp"
#include "core/page/Page.hpp"
#include "config/global_config.hpp"
#include "util/utils.hpp"
static inline std::vector<std::string> splitSqlBySemicolon(const std::string& batch) {
    std::vector<std::string> parts;
    std::string cur;
    for (char c : batch) {
        if (c == ';') { if (!cur.empty()) { parts.push_back(trim(cur)); cur.clear(); } }
        else { cur.push_back(c); }
    }
    if (!cur.empty()) parts.push_back(trim(cur));
    return parts;
}
void initFieldList(std::vector<FieldInfo> &fieldList);
void createTable(Context &context,std::string &sql);


int insertRecord(Context &context,const std::string &sql);

int updateRecord(Context &context,const std::string &sql);

bool rowMatch(std::vector<Cell>& row,
              SqlFilter& f);
std::string readRecordList(Context &context,const std::string &sql);

std::string index(const std::string& sqlBatch,Session &session);
int findRecord(Context &context,std::vector<SqlFilter> &sqlFilter,const std::function<void(Page)>& callBack);
inline Page findDataPage(Context &context,std::string &table,uint32_t &pageNo,uint64_t &key){
    Page page{context,table,pageNo};
    if(page.mPageHead.pageType == PageType::DATA){
        return page;
    }else{
        auto [found, pos] = page.findRecordIndex(key);
        IndexRecord indexRecord{};
        memcpy(&indexRecord,page.mPage->data()+page.mSlot.at(pos),sizeof(uint32_t) );
        return findDataPage(context,table,indexRecord.childPageNo,key);
    }
}

inline void clear(){
    std::vector<uint8_t> page(PAGE_SIZE);
    FileCommon::writePage(*gTableConfig["pixel"].file,2,page);

    FileHeader fileHeader{};
    FileCommon::readTableFileHeader(*gTableConfig["pixel"].file,fileHeader);

    fileHeader.lastPage = 0;
    FileCommon::saveFileHeader(*gTableConfig["pixel"].file,fileHeader);
}